package group09.android.locationtracking;

//import group09.android.locationtracking.GPS.MyLocationListener;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

public class SendLocation extends Activity {
	
	public static final String PREFS_NAME = "LocationTracking_Preferences";
	private EditText webSrv;
	private EditText longitude;
	private EditText latitude;
	private TextView status;
	private EditText accode;
	private Button btnStart;
	private Button btnStop;
	
	private String strLongitude;
	private String strLatitude;
	
	String webServUrl_pref = "http://group09.zxq.net/LocationWebserv.php";
	String accode_pref = "12345";
	
	
	private LocationManager lm;
    private LocationListener locationListener;
	
    /** Called when the activity is first created. */
    //@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webSrv = (EditText) findViewById(R.id.EditText01);
        longitude = (EditText) findViewById(R.id.EditText02);
        latitude = (EditText) findViewById(R.id.EditText03);
        status = (TextView) findViewById(R.id.TextView04);
        btnStart = (Button) findViewById(R.id.Button02);
        btnStop = (Button) findViewById(R.id.Button03);
        accode = (EditText) findViewById(R.id.EditText04);
        
        // Load preferences
        loadPreferences();
        
        //LocationManager class gets GPS locations
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        locationListener = new MyLocationListener(); // .MyLocationListener();
        
        //Toast.makeText(getBaseContext(),
        /*Toast.makeText(this, 
                "saakums", 
                Toast.LENGTH_SHORT).show();*/
        
         
    }
    
    //---------------------------------------------------------
    //Send button handler:
    public void myClickHandler(View view) {
    	try{
    		sendLocData(strLongitude, strLatitude);
    	}catch(Exception e){
    		//TODO: manage UI errors
    		status.setText("Error #94 occured");
    	}
    }
    
    //---------------------------------------------------------
    //Start button handler:
    public void onStartClick(View view) {
    	try{
    		//Saving preferences
    	    savePreferences();
    		
    	    // Add location listener
    	    //public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)
    	    //http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)
    	    //(provider, minTime (milisec), minDistance (metres), listener)
    		lm.requestLocationUpdates(
    	            LocationManager.GPS_PROVIDER, 
    	            10000, 
    	            0, 
    	            locationListener); 
    		
    		btnStop.setEnabled(true);
    		btnStart.setEnabled(false);
    		webSrv.setEnabled(false);
    		accode.setEnabled(false);
    		status.setText("GPS location sending started");
    		Toast.makeText(this, "GPS location sending started", Toast.LENGTH_LONG).show();
    		    		
    	}catch(Exception e){
    		//TODO: manage UI errors
    		status.setText("Error #95 occured");
    	}
    }
    
    //---------------------------------------------------------
    //Stop button handler:
    public void onStopClick(View view) {
    	try{
    		//Remove the listener of GPS location
    		lm.removeUpdates(locationListener);
    		
    		
    		btnStart.setEnabled(true);
    		webSrv.setEnabled(true);
    		accode.setEnabled(true);
    		btnStop.setEnabled(false);
    		//status.setText("GPS location sending stopped");
    		Toast.makeText(this, "GPS location sending stopped", Toast.LENGTH_LONG).show();
    	}catch(Exception e){
    		//TODO: manage UI errors
    		status.setText("Error #96 occured");
    	}
    }
    
    //---------------------------------------------------------
    //Sending location data to the server
    private boolean sendLocData(String lng, String lat){
    	String result_info = "";
    	String strDate = "";
    	try{
	    	status.setText("Sending location...");
	    	String url = webSrv.getText().toString() + 
	    		"?accode=" + accode.getText().toString() +
	    		"&longitude=" + lng +
	    		"&latitude=" + lat;
	    	status.setText(url);
	    	//Toast.makeText(this, url, Toast.LENGTH_LONG).show();
	    	Iface sendLocData = new Iface();
	    	//Connect to the Web Service through Iface object
	    	String result = sendLocData.connect(url);
	    	//Thread.sleep(2000);
	    	//Toast.makeText(this, result, Toast.LENGTH_LONG).show();
	    	
	    	//Analyze the result of the sent location
	    	int intErrCode = 100;
    		try{
    			intErrCode = Integer.parseInt(result);
    		}catch (Exception e){
    			intErrCode = 100;
    		}
	    	//if all is fine
	    	if (intErrCode == 0){
	    		//Show result in a status text label in the application;
	    		Date dat = new Date();
	    		strDate = Integer.toString(dat.getYear() + 1900)+"."+
	    			Integer.toString(dat.getMonth() + 1)+"."+
	    			Integer.toString(dat.getDate())+" "+
	    			Integer.toString(dat.getHours())+":"+
	    			Integer.toString(dat.getMinutes())+":"+
	    			Integer.toString(dat.getSeconds());
	    		//result_info =  + 
	    		result_info = " [" + strDate + "] Location saved\n Longitude: " + lng + "\n Latitude: " + lat;
	    	}else{
	    		//Text to be displayed to the user
	    		result_info = "Error: " + showErrMsg(intErrCode);
	    	}
	    	status.setText(result_info);
	    	
	    	//if ( status != null )
	    		//status.setText(result);
	    	/*else
	    		Toast.makeText(this, "result: " + result, Toast.LENGTH_LONG).show();*/
	    	//Thread.sleep(2000);
	    	//status.setText("Location sent");
	    	//Toast.makeText(this, "Location sent, result: " + result, Toast.LENGTH_LONG).show();
	    	
    	}catch(Exception e){
    		status.setText("Error #97 occured");
    	}
    	return true;
    }
    
  //----------------------------------------------------
    private boolean loadPreferences(){
	    try{
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    webServUrl_pref = settings.getString("webServUrl", "http://group09.zxq.net/LocationWebserv.php");
	    accode_pref = settings.getString("accode", "12345");
	    
	    webSrv.setText(webServUrl_pref);
	    accode.setText(accode_pref);
	    
	    }catch(Exception e){
	    	status.setText("Error #98 occured");
	    }
	    
	    /*Toast.makeText(getBaseContext(), 
                "Loaded preferences", 
                Toast.LENGTH_SHORT).show();*/
	    
	    return true;
    }
    
    //----------------------------------------------------
    private boolean savePreferences(){
    	try{
	    	// We need an Editor object to make preference changes.
	        // All objects are from android.context.Context
	        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	        SharedPreferences.Editor editor = settings.edit();
	        
	        //get the webserv URL from the text input
	        webServUrl_pref = webSrv.getText().toString();
	        editor.putString("webServUrl", webServUrl_pref);
	        accode_pref = accode.getText().toString();
	        editor.putString("accode", accode_pref);
	
	        // ommit the edits
	        editor.commit();
	        
	        /*Toast.makeText(getBaseContext(), 
                    "Saved preferences", 
                    Toast.LENGTH_SHORT).show();*/
    	
	    }catch(Exception e){
	    	status.setText("Error #99 occured");
	    }
        
    	return true;
    }
    
    //----------------------------------------------------
    //When the application is stopped
    //@Override
    protected void onStop(){
       super.onStop();
      
      //Saving preferences
      savePreferences();
    }
    
    //----------------------------------------------------
    private String showErrMsg(int errNr){
		String msg = "";
		switch (errNr) {
			case 0: msg = " all is ok!"; break;
			case 1: msg = " cannot connect to database"; break;
			case 2: msg = " cannot select database"; break;
			case 3: msg = " no attributes passed"; break;
			case 4: msg = " server side error"; break;
			case 90: msg = " Incorrect server response"; break;
			case 91: msg = " Incorrect server response"; break;
			case 92: msg = " Could not connect"; break;
			case 93: msg = " Could not connect"; break;
			case 94: msg = " Send button hanlder"; break;
			case 95: msg = " Start button handler"; break;
			case 96: msg = " Stop button handler"; break;
			case 97: msg = " Send data"; break;
			case 98: msg = " Load preferences"; break;
			case 99: msg = " Save preferences"; break;
			case 100: msg = " Technical problem"; break;
			case 910: msg = " Could not connect"; break;
			default: msg = " Data not sent"; break;
		}
		return msg;
	}
    
    //---------------------------------------------------------
    //Saves application preferences
    /*@Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }*/
    /*//---------------------------------------------------------
    //Replace non-URL characters (, .) with _
    private String coordForUrl(String coord){
    	coord.replace(',', '_');
    	coord.replace('.', '_');
    	return coord;
    }*/
    //---------------------------------------------------------
    //listens to GPS signal - location messge coming from hadware
    public class MyLocationListener implements LocationListener
    {
        //@Override
        //when the location is changed, this method is called
        //it gets GPS coordinates, saves them into variables/fields and calls sending to the server;
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                /*Toast.makeText(getBaseContext(), 
                    "Location changed : Lat: " + loc.getLatitude() + 
                    " Lng: " + loc.getLongitude(), 
                    Toast.LENGTH_SHORT).show();*/
                
            	strLongitude = Double.toString(loc.getLongitude());
            	strLatitude = Double.toString(loc.getLatitude());
            		
                longitude.setText(strLongitude);
                latitude.setText(strLatitude);
                sendLocData(strLongitude, strLatitude);
            }
            //status.setText("onLocationChanged");
        }

        //@Override
        public void onProviderDisabled(String provider) {

        	/*Toast.makeText(getBaseContext(), 
                    "onProviderDisabled", 
                    Toast.LENGTH_SHORT).show();*/
        }

        //@Override
        public void onProviderEnabled(String provider) {

        	/*Toast.makeText(getBaseContext(), 
                    "onProviderEnabled", 
                    Toast.LENGTH_SHORT).show();*/
        	//status.setText("onProviderEnabled");
        }

        //@Override
        public void onStatusChanged(String provider, int status_int, 
            Bundle extras) {

        	/*Toast.makeText(getBaseContext(), 
                    "onStatusChanged", 
                    Toast.LENGTH_SHORT).show();*/
        	//status.setText("onStatusChanged");
        }
    }
}